package com.s59.rbac.shiro;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s59.rbac.entity.Menu;
import com.s59.rbac.entity.Role;
import com.s59.rbac.entity.User;
import com.s59.rbac.service.IMenuService;
import com.s59.rbac.service.IRoleService;
import com.s59.rbac.service.IUserService;
import com.s59.rbac.service.impl.PermssionService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;
    @Autowired
    private PermssionService permssionService;

    public ShiroRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
        super(hashedCredentialsMatcher);
    }

    /**
     *  鉴权时调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo =  new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(permssionService.getRoleKeys(user.getNickName()));
        authorizationInfo.addStringPermissions(permssionService.getPerms(user.getUserName()));
        return authorizationInfo;
    }




    /**
     * 登录时调用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 根据用户名找到用户
        String userName = (String) authenticationToken.getPrincipal();
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, userName));
        if (user != null){
            return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());

        }
        return null;
    }
}
